import axios from 'axios';
import { getToken, isTokenExpired, removeToken, removeUserInfo } from '../utils/jwtUtils';

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 使用Vite代理路径
  timeout: 10000,
  withCredentials: true, // 允许跨域请求携带凭证
  headers: {
    'Content-Type': 'application/json',
    // 添加额外的头部信息，如果后端需要
    'X-Requested-With': 'XMLHttpRequest'
  },
});

// 在请求拦截器中添加日志，用于调试
api.interceptors.request.use(
  async (config) => {
    console.log('发送请求到:', config.baseURL + config.url);
    console.log('请求头:', config.headers);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 创建用于刷新token的axios实例（不使用拦截器，避免循环调用）
const refreshApi = axios.create({
  baseURL: '/api', // 使用Vite代理路径
  timeout: 10000,
  withCredentials: true,
});

// 是否正在刷新token的标志
let isRefreshing = false;
// 等待刷新token的请求队列
let refreshSubscribers = [];

// 将请求添加到队列
const addRefreshSubscriber = (callback) => {
  refreshSubscribers.push(callback);
};

// 通知所有等待的请求继续执行
const notifyRefreshSubscribers = (newToken) => {
  refreshSubscribers.forEach((callback) => callback(newToken));
  refreshSubscribers = [];
};

// 刷新token的方法
const refreshToken = async () => {
  try {
    // 获取当前token（用于刷新）
    const currentToken = getToken();
    if (!currentToken) {
      throw new Error('No token available for refresh');
    }
    
    // 发送刷新token请求
    const response = await refreshApi.post('/auth/refresh-token', {
      token: currentToken
    });
    
    const { token } = response.data;
    if (token) {
      localStorage.setItem('token', token);
      return token;
    }
    
    throw new Error('Failed to refresh token');
  } catch (error) {
    console.error('Token refresh failed:', error);
    // 刷新失败，清除认证信息
    removeToken();
    removeUserInfo();
    // 跳转到登录页
    window.location.href = '/login';
    throw error;
  }
};

// 请求拦截器 - 添加token和处理token过期
api.interceptors.request.use(
  async (config) => {
    // 从localStorage中获取token
    let token = getToken();
    
    if (token) {
      // 检查token是否即将过期，如果是则刷新
      if (isTokenExpired(token)) {
        if (!isRefreshing) {
          isRefreshing = true;
          try {
            token = await refreshToken();
          } finally {
            isRefreshing = false;
          }
        }
        
        // 如果正在刷新token，等待刷新完成
        if (isRefreshing) {
          return new Promise((resolve) => {
            addRefreshSubscriber((newToken) => {
              config.headers.Authorization = `Bearer ${newToken}`;
              resolve(config);
            });
          });
        }
      }
      
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理token过期等情况
api.interceptors.response.use(
  (response) => {
    // 检查响应中是否包含新的token，如果有则更新
    if (response.data && response.data.token) {
      localStorage.setItem('token', response.data.token);
    }
    // 直接返回响应数据
    return response;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 处理401错误，尝试刷新token
    if (error.response && error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      if (!isRefreshing) {
        isRefreshing = true;
        try {
          const newToken = await refreshToken();
          
          // 重试原始请求
          originalRequest.headers.Authorization = `Bearer ${newToken}`;
          notifyRefreshSubscribers(newToken);
          return api(originalRequest);
        } catch (refreshError) {
          console.error('Failed to retry request after token refresh:', refreshError);
          return Promise.reject(refreshError);
        } finally {
          isRefreshing = false;
        }
      } else {
        // 如果已经在刷新token，等待刷新完成后重试
        return new Promise((resolve) => {
          addRefreshSubscriber((newToken) => {
            originalRequest.headers.Authorization = `Bearer ${newToken}`;
            resolve(api(originalRequest));
          });
        });
      }
    }
    
    // 处理其他错误情况
    if (error.response) {
      // 服务器返回错误状态码
      switch (error.response.status) {
        case 403:
          // 禁止访问，权限不足
          console.error('权限不足，请联系管理员');
          break;
        case 404:
          // 请求的资源不存在
          console.error('请求的资源不存在');
          break;
        case 500:
          // 服务器内部错误
          console.error('服务器内部错误，请稍后再试');
          break;
        default:
          console.error('请求失败:', error.response.data?.message || '未知错误');
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      console.error('网络错误，请检查网络连接');
    } else {
      // 请求配置出错
      console.error('请求配置错误:', error.message);
    }
    return Promise.reject(error);
  }
);

// 导出api实例
export default api;

// 导出其他API服务函数
export const authService = {
  login: (credentials) => api.post('/auth/login', credentials),
  loginWithCode: (data) => api.post('/auth/login/code', data),
  sendVerificationCode: (phone) => api.post('/auth/send-code', { phone }),
  logout: () => api.post('/auth/logout'),
};

export const deviceService = {
  getAll: (filters = {}) => api.get('/devices', { params: filters }),
  getById: (id) => api.get(`/devices/${id}`),
  create: (deviceData) => api.post('/devices', deviceData),
  update: (id, deviceData) => api.put(`/devices/${id}`, deviceData),
  delete: (id) => api.delete(`/devices/${id}`),
  generateQrCode: (id) => api.post(`/devices/${id}/qr-code`),
  export: (filters = {}) => api.get('/devices/export/excel', { 
    params: filters,
    responseType: 'blob'
  }),
};

export const userService = {
  getCurrentUser: () => api.get('/user/profile'),
  updateProfile: (profileData) => api.put('/user/profile', profileData),
};

export const logService = {
  getOperationLogs: (filters = {}) => api.get('/logs/operation', { params: filters }),
};